package com.xie.o2o.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @create: xie
 */
public class ImageUtil {
    //classpath资源路径
    private static String basePath = PathUtil.getImgBasePath();
    private static final SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();

    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 将MultipartFile转换成File类
     *
     * @param cfile
     * @return
     */
    public static File transferToFile(MultipartFile cfile) {
        File file = new File(cfile.getOriginalFilename());
        try {
            cfile.transferTo(file);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 处理缩略图，并返回新生成图片的路径
     *
     * @param shopImg    上传的文件
     * @param targetAddr 目标路径
     * @return
     */
    public static String generateThumbnail(MultipartFile shopImg, String targetAddr) {
        //新文件名
        String realFileName = getRandomFileName();
        //原文件扩展名
        String extension = getFileExtension(shopImg);
        //处理目标路径
        makeDirPath(targetAddr);
        //拼接目标相对路径
        String relativeAddr = targetAddr + realFileName + extension;
        logger.debug("当前相对路径：" + relativeAddr);
        //存放图片位置的绝对路径
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("当前绝对路径：" + PathUtil.getImgBasePath() + relativeAddr);
        try {
            //压缩图片，添加水印，
            Thumbnails.of(shopImg.getInputStream()).size(200, 200)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/1.png")), 0.25f)
                    .outputQuality(0.8f).toFile(dest);
        } catch (IOException e) {
            logger.error(e.toString());
            throw new RuntimeException("创建缩略图失败："+e.toString());
        }
        return relativeAddr;
    }

    /**
     * 处理商品详情图
     *
     * @param shopImg
     * @param targetAddr
     * @return
     */
    public static String generateNormalImg(MultipartFile shopImg, String targetAddr) {
        //新文件名
        String realFileName = getRandomFileName();
        //原文件扩展名
        String extension = getFileExtension(shopImg);
        //处理目标路径
        makeDirPath(targetAddr);
        //拼接目标相对路径
        String relativeAddr = targetAddr + realFileName + extension;
        logger.debug("当前相对路径：" + relativeAddr);
        //存放图片位置的绝对路径
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("当前绝对路径：" + PathUtil.getImgBasePath() + relativeAddr);
        try {
            //压缩图片，添加水印，
            Thumbnails.of(shopImg.getInputStream()).size(337, 640)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/1.png")), 0.25f)
                    .outputQuality(0.9f).toFile(dest);
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径所涉及的目录，多级文件夹都要创建
     *
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String realPath = PathUtil.getImgBasePath() + targetAddr;
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }


    /**
     * 获取输入文件的扩展名
     */
    private static String getFileExtension(MultipartFile shopImg) {
        String originalFilename = shopImg.getOriginalFilename();
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    /**
     * 生成随机文件名,当前时间+五位随机数
     */
    public static String getRandomFileName() {
        //获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        return dateformat.format(new Date()) + rannum;
    }

    /**
     * 删除路径下图片
     *
     * @param path
     */
    public static void deleteFileOrPath(String path) {
        File fileOrPath = new File(PathUtil.getImgBasePath() + path);
        if (fileOrPath.exists()) {
            if (fileOrPath.isDirectory()) {
                File[] files = fileOrPath.listFiles();
                for (int i = 0; i < files.length; i++) {
                    files[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }
}
